#include "stl_parser.hpp"
#include <string>

using namespace std;

const char*
  t_solid=    "solid",
  t_normal=   "normal",
  t_facet=    "facet",
  t_outer=    "outer",
  t_loop=     "loop",
  t_vertex=   "vertex",
  t_endsolid= "endsolid";


bool stl_parser::cmp(const string &a, const string &b)
{
  if(a.size()!=b.size())
    return false;
  
  string::const_iterator pa=a.begin();
  string::const_iterator pb=b.begin();
  while(pa!=a.end() && pb!=b.end())
    {
      
    if(toupper(*pa)!=toupper(*pb))
      return false;

    pa++;
    pb++;

    
    }
  
  return true;
}



bool stl_parser::parse()
{

   
  if(parse_header())
    {
      while(!in.eof())
	{
	  string toc;
	  in>>toc;
	  if(toc==t_endsolid)
	      return true;
	  if(!parse_facet())
	    return false;
	}
      return true;
      
    }
  else
    return false;
  
}

bool stl_parser::parse_header()
{
   string t1;
   in>>t1;
   char sname[255];
   
   in.getline(sname,255);
   name=string(sname);
   
   if(!cmp(t1,t_solid))
     return false;

   return true;
   
}

bool stl_parser::parse_facet()
{
  string t1,t2;
  in>>t1;
  if(cmp(t1,t_normal))
    {
      double x,y,z;
      
      if(!readvertex(x,y,z))
	return false;
    }
  else
    {
      return false;
    }

  in>>t1>>t2;
  if(!cmp(t1,t_outer) || !cmp(t2,t_loop))
    return false;

  triangle.clear();
  for(int i=0; i<3; i++)
    {
      in>>t1;
      if(!cmp(t1,t_vertex))
	return false;

      double x,y,z;
      if(!readvertex(x,y,z))
	return false;
      
      triangle.push_back(x);
      triangle.push_back(y);
      triangle.push_back(z);
      
    }
  in>>t1;
  //check endloop;
  in>>t1;
  //check enfacet
  got_triangle(triangle);
  return true;
  
  
}


bool stl_parser::readvertex(double &x,double &y,double &z)
{
  in>>x>>y>>z;
  
  return true;
}
